package models

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type LocalTime time.Time

// Time 数据格式解析
func (t *LocalTime) MarshalJSON() ([]byte, error) {
	h, _ := time.ParseDuration("1h")
	tTime := time.Time(*t).Add(8 * h)
	return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
}

func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time

	tlt := time.Time(t)
	// 判断时间是否和默认0时间相同
	if tlt.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return tlt, nil
}

func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

type BaseModel struct {
	Id         int64      `json:"id" form:"id" gorm:"id;primary_key;AUTO_INCREMENT"`
	CreateTime *LocalTime `json:"create_time,omitempty"  form:"create_time" gorm:"column:create_time;default:null;omitempty;autoCreateTime"`
	WriteTime  *LocalTime `json:"write_time,omitempty"  form:"write_time" gorm:"column:write_time;default:null;omitempty;autoUpdateTime"`
}
